package service;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import entity.PapelUsuario;
import entity.PermissaoFuncionalidade;
import entity.Usuario;

@Service("userDetailsAdapter")
public class UserDetailsAdapter {

	private Long id;

	@Transactional(readOnly = true)
	User buildUserFromUserEntity(Usuario usuario) {
		String username = usuario.getUsername();
		String password = usuario.getPassword();
		boolean enabled = usuario.isAtivo();
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		for (PapelUsuario papel : usuario.getListaPapeisUsuario()) {

			for (PermissaoFuncionalidade permissao : papel.getListaPermissoes()) {
				authorities
						.add(new SimpleGrantedAuthority(permissao.getNome()));
			}
		}

		this.id = usuario.getId();

		final User user = new org.springframework.security.core.userdetails.User(
				username, password, enabled, accountNonExpired,
				credentialsNonExpired, accountNonLocked, authorities);
		return user;
	}

	public Long getId() {
		return id;
	}

}
